//
//  DiarySectionOCTableViewCell.m
//  MoodDiary
//
//  Created by MoodDiary on 2020/12/4.
//

#import "DiarySectionOCTableViewCell.h"

#import "DiaryOCTableViewCell.h"

#import "MoodDiary-Swift.h"

#import "DiarySectionHeaderOCView.h"

@interface DiarySectionOCTableViewCell () <UITableViewDelegate, UITableViewDataSource, DiaryOCTableViewCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bgView;

@end

@implementation DiarySectionOCTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.bgView.layer.cornerRadius = 10.0;
    self.bgView.layer.shadowColor = [UIColor colorWithWhite:0.6 alpha:0.4].CGColor;
    self.bgView.layer.shadowOffset = CGSizeMake(0, 0);
    self.bgView.layer.shadowOpacity = 1.0;
    self.bgView.layer.shadowRadius = 2.0;
    
    self.tableView.layer.cornerRadius = 10.0;
    self.tableView.layer.masksToBounds = YES;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"DiaryOCTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"DiaryOCTableViewCell"];
}

- (void)setDaysDic:(NSDictionary *)daysDic {
    _daysDic = daysDic;
    
    NSLog(@"daysDic === %@", daysDic);
    
    NSInteger day = [daysDic[@"day"] integerValue];
    NSInteger last = [daysDic[@"last"] integerValue];
    
    if (last > day + 1) {
        self.bgViewTop.constant = 20.0 + 30.0;
        
        self.label.text = [NSString stringWithFormat:@"%ld天没有记录", last - day - 1];
        self.daysView.hidden = NO;
    } else {
        self.bgViewTop.constant = 20.0;
        self.daysView.hidden = YES;
    }
}

-(void)setCompareDayStr:(NSString *)compareDayStr{
    
    _compareDayStr = compareDayStr;
    if (compareDayStr.intValue > 1) {
        self.bgViewTop.constant = 20.0 + 30.0;
        self.label.text = [NSString stringWithFormat:@"%d天没有记录", compareDayStr.intValue-1];
        self.daysView.hidden = NO;
    }else{
        self.bgViewTop.constant = 20.0;
        self.daysView.hidden = YES;
        self.label.text = @"";
    }
    
}

- (void)setDayArray:(NSArray *)dayArray {
    _dayArray = dayArray;
    [self.tableView reloadData];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.tableView reloadData];
//    });
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
//    NSDictionary *tempDict = _dayArray[section];
//    NSDictionary *dict = tempDict[@"dayDatas"];
    return _dayArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_dayArray.count == 0) {
        return 0;
    }
    if ([_dayArray[indexPath.row][@"reasonDetailStr"] length] > 0) {
        
        NSString *reasonDetailStr = _dayArray[indexPath.row][@"reasonDetailStr"];
        if ([reasonDetailStr containsString:@"isAttributedString"]) {
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
            NSString *folderPath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",_dayArray[indexPath.row][@"timeStampStr"]]];
            
            if ([fileManager fileExistsAtPath:folderPath]) {
            
                NSData *data = [fileManager contentsAtPath:folderPath];
                NSAttributedString *attr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                
                
                __block NSMutableAttributedString *mutableAttr = [[NSMutableAttributedString alloc] initWithAttributedString:attr];

                [attr enumerateAttributesInRange:NSMakeRange(0, attr.string.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary<NSAttributedStringKey,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {

                    NSTextAttachment *textAtt = attrs[@"NSAttachment"];

                    if (textAtt) {

//                        UIImage *tempImage = textAtt.image;
//
//                        CGFloat scale = tempImage.size.width / tempImage.size.height;
//                        CGFloat height = 80.0;
//                        CGFloat width = scale * height;
//                        if (scale > 1){
//                            width = 80;
//                            height = width/scale;
//                        }
//
//                        textAtt.bounds = CGRectMake(0, 0, width, height);
                        [mutableAttr replaceCharactersInRange:range withAttributedString:[[NSAttributedString alloc]initWithString:@""]];
                    }

                }];
//
//                return 90.0 + [attr boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH - 75.0 - 22.0 - 30.0 * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height+25.0;
                return 90.0 + [[mutableAttr.string stringByTrimmingCharactersInSet:NSCharacterSet.newlineCharacterSet] boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH - 75.0 - 22.0 - 30.0 * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]} context:nil].size.height + 25.0;
            }else{
                
                return 90.0 + [reasonDetailStr boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH - 75.0 - 22.0 - 30.0 * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]} context:nil].size.height + 25.0;
            }
            
        }else{
            
            return 90.0 + [reasonDetailStr boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH - 75.0 - 22.0 - 30.0 * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]} context:nil].size.height + 25.0;
        }
        
    }
    return 90.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 35.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    DiarySectionHeaderOCView *headView = [[NSBundle mainBundle] loadNibNamed:@"DiarySectionHeaderOCView" owner:self options:nil].lastObject;
    headView.bounds = CGRectMake(0, 0, DEF_SCREEN_WIDTH, 35.0);
    
    if (_dayArray.count == 0) {
        return headView;
    }
    headView.label.text = [[[NSString getMonthAndDay:_dayArray[section][@"timeStampStr"]] stringByAppendingString:@" "] stringByAppendingString:[NSString dateWeekWithTimeStamp:_dayArray[section][@"timeStampStr"]]];
    headView.imgV.image = [UIImage imageNamed: _dayArray[section][@"weatherStr"]];
    
    return headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DiaryOCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DiaryOCTableViewCell"];
    NSLog(@"DiarySectionOCTableViewCell-----%ld---%ld",indexPath.section,indexPath.row);
    NSDictionary *dict = _dayArray[indexPath.row];
    
    UIImage *showImg = [UIImage imageNamed: dict[@"moodStr"]];
    if (showImg) {
        cell.imgV.image = showImg;
    } else {
        NSMutableArray *imgArr = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:@"KUSERFeelingImagesArrName"]];
        NSArray *imgDeletedArray = [[NSUserDefaults standardUserDefaults] arrayForKey:@"KUSERFeelingDeletedImagesArrName"];
        [imgArr addObjectsFromArray:imgDeletedArray];
        
        for (NSDictionary *cacheDict in imgArr) {
            if ([dict[@"moodStr"] isEqual:cacheDict[@"text"]]) {
                cell.imgV.image = [UIImage imageNamed: cacheDict[@"imgName"]];
                break;
            }
        }
    }
    
    NSString *moodStr = [dict[@"moodStr"] stringByAppendingString:@"  "];
    
    moodStr = [moodStr stringByAppendingString:[NSString getHourAndMinute:dict[@"timeStampStr"]]];
    NSMutableAttributedString *mS = [[NSMutableAttributedString alloc] initWithString:moodStr];
    if ([dict[@"moodStr"] isEqualToString:@"不知道"]) {
        [mS addAttributes:@{NSForegroundColorAttributeName: [UIColor hexColorWithHex:[self colorWithType:@"不好描述"]], NSFontAttributeName: [UIFont systemFontOfSize:19.0]} range:NSMakeRange(0, 4)];
    } else {
        [mS addAttributes:@{NSForegroundColorAttributeName: [UIColor hexColorWithHex:[self colorWithType:dict[@"moodStr"]]], NSFontAttributeName: [UIFont systemFontOfSize:19.0]} range:NSMakeRange(0, [dict[@"moodStr"] length])];
    }
    
    cell.titleLabel.attributedText = mS;
    
    cell.array = dict[@"reasonArray"];
    cell.delegate = self;
    cell.indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:_currentSection];
    
    if ([dict[@"reasonDetailStr"] length] > 0) {
        
        NSString *reasonDetailStr = dict[@"reasonDetailStr"] ;
        if ([reasonDetailStr containsString:@"isAttributedString"]) {
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
            NSString *folderPath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",dict[@"timeStampStr"]]];
            
            if ([fileManager fileExistsAtPath:folderPath]) {
            
                NSData *data = [fileManager contentsAtPath:folderPath];
                NSAttributedString *attr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                
                //若列表需要显示图片，打开下列代码
                __block NSMutableAttributedString *mutableAttr = [[NSMutableAttributedString alloc] initWithAttributedString:attr];

                [attr enumerateAttributesInRange:NSMakeRange(0, attr.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary<NSAttributedStringKey,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {

                    NSTextAttachment *textAtt = attrs[@"NSAttachment"];

                    if (textAtt) {

//                        UIImage *tempImage = textAtt.image;
//
//                        CGFloat scale = tempImage.size.width / tempImage.size.height;
//                        CGFloat height = 80.0;
//                        CGFloat width = scale * height;
//                        if (scale > 1){
//                            width = 80;
//                            height = width/scale;
//                        }
//
//                        textAtt.bounds = CGRectMake(0, 0, width, height);
//                        [mutableAttr replaceCharactersInRange:range withAttributedString:[NSAttributedString attributedStringWithAttachment:textAtt]];
                        [mutableAttr replaceCharactersInRange:range withAttributedString:[[NSAttributedString alloc]initWithString:@""]];
                    }



                }];
//                cell.contentTextView.attributedText = mutableAttr.copy;
//                if ([reasonDetailStr hasPrefix:@"1"]) {
//                    cell.contentTextView.textAlignment = NSTextAlignmentCenter;
//                }else if ([reasonDetailStr hasPrefix:@"2"]) {
//                    cell.contentTextView.textAlignment = NSTextAlignmentRight;
//                }else{
//                    cell.contentTextView.textAlignment = NSTextAlignmentLeft;
//                }
                NSString *str = [mutableAttr.string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
                
                cell.contentTextView.text = str;
                cell.contentTextView.textAlignment = NSTextAlignmentLeft;
            }
        }else{
            cell.contentTextView.text = dict[@"reasonDetailStr"];
            cell.contentTextView.textAlignment = NSTextAlignmentLeft;
        }
//        cell.contentLabel.hidden = NO;
        cell.contentTextView.hidden = NO;
    } else {
        cell.contentTextView.hidden = YES;
//        cell.contentLabel.hidden = YES;
    }
    
    
    
    
    if (indexPath.row == 0) {
        cell.lineView.hidden = NO;
    } else {
        cell.lineView.hidden = YES;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([self.delegate respondsToSelector:@selector(checkDetailDiaryWithData:index:)]) {
        
        NSDictionary *dict = _dayArray[indexPath.row];
        [self.delegate checkDetailDiaryWithData:dict index:self.currentPart];
    }
    
}



- (NSString *)colorWithType:(NSString *)typeStr {
    if ([typeStr isEqualToString:@"开心"]) {
        return @"#FDB851";
    }
    if ([typeStr isEqualToString:@"惊喜"]) {
        return @"#A7D16F";
    }
    if ([typeStr isEqualToString:@"得意"]) {
        return @"#35BD5E";
    }
    if ([typeStr isEqualToString:@"甜蜜"]) {
        return @"#FF804B";
    }
    if ([typeStr isEqualToString:@"暖心"]) {
        return @"#E785A7";
    }
    if ([typeStr isEqualToString:@"充实"]) {
        return @"#FDB851";
    }
    if ([typeStr isEqualToString:@"平静"]) {
        return @"#F49CBA";
    }
    if ([typeStr isEqualToString:@"无聊"]) {
        return @"#848CB4";
    }
    if ([typeStr isEqualToString:@"尴尬"]) {
        return @"#FDB851";
    }
    if ([typeStr isEqualToString:@"不安"]) {
        return @"#848CB4";
    }
    if ([typeStr isEqualToString:@"伤心"]) {
        return @"#97C3DD";
    }
    if ([typeStr isEqualToString:@"生气"]) {
        return @"#F18757";
    }
    if ([typeStr isEqualToString:@"流泪"]) {
        return @"#6FB1ED";
    }
    if ([typeStr isEqualToString:@"分裂"]) {
        return @"#FDB851";
    }
    if ([typeStr isEqualToString:@"疲惫"]) {
        return @"#97C3DD";
    }
    if ([typeStr isEqualToString:@"孤独"]) {
        return @"#97C3DD";
    }
    if ([typeStr isEqualToString:@"梦境"]) {
        return @"#848CB4";
    }
    if ([typeStr isEqualToString:@"不好描述"]) {
        return @"#A7D16F";
    }
    return  @"#FDB851";
}

- (void)diaryOCTableViewCellSelectIndex:(nonnull NSIndexPath *)indexPath {
    
    if ([_dayArray[indexPath.row][@"timeStampStr"] length] > 0) {
        NSString *timeStampStr = _dayArray[indexPath.row][@"timeStampStr"];
        [self.delegate diarySectionOCTableViewCellSelectPart:self.currentPart andSection:indexPath.section andRow:indexPath.row andDeletedDiaryStamp: timeStampStr];
    }
}

@end
